package com.yxj.Practice6;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

    public class MyRunnable implements Runnable{
        Socket socket;

    public MyRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            while(true) {

                ///3.读取数据并保存到本地文件中
                BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                String name = UUID.randomUUID().toString().replace("-","");

                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\Ccode\\java-se\\Mysocketnet\\"+name+".png"));
                int len;
                byte[] bytes = new byte[1024];
                while((len = bis.read(bytes)) != -1) {
                    bos.write(bytes,0,len);
                }

                //4.回写数据
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                bw.write("上传成功");
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

        public static class Client {
            public static void main(String[] args) throws IOException {
                //1.创建Socket对象，并连接服务器
                Socket socket = new Socket("192.168.56.1", 10000);

                //2.读取本地文件中的数据，并写到服务器中
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\桌面\\122.png"));
                BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
                byte[] bytes = new byte[1024];
                int len;
                while((len=bis.read(bytes)) != -1) {
                    bos.write(bytes,0,len);
                }

                //
                socket.shutdownOutput();

                //3.接收服务器的回写数据
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = br.readLine();
                System.out.println(line);

                //
                socket.close();

            }
        }
    }